/**
 * 登录页面逻辑
 */

const { ipcRenderer } = require('electron');
const log = require('electron-log');
const { 
  SERVER_URL, 
  showNotification, 
  saveUserData, 
  getUserData,
  navigateToPage 
} = require('../utils/common');

// DOM元素 - 将在页面加载后获取
let loginForm, usernameInput, passwordInput, captchaInput;
let loginBtn, errorMsg, togglePasswordBtn, refreshCaptchaBtn;
let captchaDisplay, rememberMeCheckbox;
let emailInput, emailRow;
let serverStatusEl, switchToRegisterEl, switchToLoginEl, formTitleEl, forgotPasswordEl;

// 验证码
let currentCaptcha = '';
let isRegisterMode = false;

// 页面加载时初始化
window.addEventListener('DOMContentLoaded', () => {
  console.log('登录页面加载中...');
  
  // 获取DOM元素
  loginForm = document.getElementById('login-form');
  usernameInput = document.getElementById('username');
  passwordInput = document.getElementById('password');
  captchaInput = document.getElementById('captcha-input');
  loginBtn = document.getElementById('login-btn');
  errorMsg = document.getElementById('error-msg');
  togglePasswordBtn = document.getElementById('toggle-password');
  refreshCaptchaBtn = document.getElementById('refresh-captcha');
  captchaDisplay = document.getElementById('captcha-display');
  rememberMeCheckbox = document.getElementById('remember-me');
  emailInput = document.getElementById('email');
  emailRow = document.getElementById('email-row');
  serverStatusEl = document.getElementById('server-status');
  switchToRegisterEl = document.getElementById('switch-to-register');
  switchToLoginEl = document.getElementById('switch-to-login');
  formTitleEl = document.getElementById('form-title');
  forgotPasswordEl = document.getElementById('forgot-password');
  
  // 验证DOM元素是否正确获取
  if (!loginForm || !usernameInput || !passwordInput) {
    console.error('关键DOM元素未找到！');
    log.error('登录页面DOM元素加载失败');
    return;
  }
  
  console.log('DOM元素加载成功');
  
  // 检查是否已登录
  const userData = getUserData();
  if (userData) {
    console.log('用户已登录，跳转到主页');
    window.location.href = 'base.html';  // 直接跳转到新架构主页
    return;
  }
  
  // 初始化验证码
  currentCaptcha = generateCaptcha();
  updateCaptchaDisplay();

  // 加载记住的用户名
  const rememberedUsername = localStorage.getItem('rememberedUsername');
  if (rememberedUsername) {
    usernameInput.value = rememberedUsername;
    rememberMeCheckbox.checked = true;
  }

  // 绑定事件
  initializeEventListeners();
  
  // 检测服务器状态
  checkServerStatus();
  console.log('登录页面初始化完成');
});

// 生成验证码
function generateCaptcha() {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let captcha = '';
  for (let i = 0; i < 4; i++) {
    captcha += chars[Math.floor(Math.random() * chars.length)];
  }
  return captcha;
}

// 更新验证码显示
function updateCaptchaDisplay() {
  if (captchaDisplay) {
    captchaDisplay.textContent = currentCaptcha;
  }
}

// 显示错误消息
function showError(message) {
  if (errorMsg) {
    errorMsg.textContent = message;
    errorMsg.classList.remove('hidden');
    setTimeout(() => {
      errorMsg.classList.add('hidden');
    }, 5000);
  }
}

// 初始化事件监听器
function initializeEventListeners() {
  console.log('绑定事件监听器...');
  
  // 模式切换：去注册
  switchToRegisterEl?.addEventListener('click', (e) => {
    e.preventDefault();
    setMode('register');
  });

  // 模式切换：去登录
  switchToLoginEl?.addEventListener('click', (e) => {
    e.preventDefault();
    setMode('login');
  });

  // 忘记密码
  forgotPasswordEl?.addEventListener('click', (e) => {
    e.preventDefault();
    showNotification('请联系管理员重置密码或稍后在设置中添加找回流程', 'info');
  });
  
  // 刷新验证码
  refreshCaptchaBtn.addEventListener('click', () => {
    console.log('刷新验证码');
    currentCaptcha = generateCaptcha();
    updateCaptchaDisplay();
    captchaInput.value = '';
    
    // 添加旋转动画
    refreshCaptchaBtn.style.transform = 'rotate(360deg)';
    setTimeout(() => {
      refreshCaptchaBtn.style.transform = '';
    }, 300);
  });

  // 切换密码可见性
  togglePasswordBtn.addEventListener('click', () => {
    console.log('切换密码可见性');
    const type = passwordInput.type === 'password' ? 'text' : 'password';
    passwordInput.type = type;
    togglePasswordBtn.textContent = type === 'password' ? '👁️' : '🙈';
  });

  // 登录/注册 表单提交
  loginForm.addEventListener('submit', async (e) => {
    console.log('表单提交事件触发');
    e.preventDefault();

    const username = usernameInput.value.trim();
    const password = passwordInput.value;
    const captcha = captchaInput.value.trim().toUpperCase();
    const email = emailInput?.value?.trim();

    console.log(`尝试登录: ${username}`);

    // 验证输入
    if (!username || !password) {
      showError('请输入用户名和密码');
      return;
    }

    if (!captcha) {
      showError('请输入验证码');
      return;
    }

    // 禁用按钮，显示加载状态
    loginBtn.disabled = true;
    loginBtn.innerHTML = `<span class="loading"></span> ${isRegisterMode ? '注册中...' : '登录中...'} `;
    errorMsg.classList.add('hidden');

    // 先验证本地验证码（可选的前端验证）
    const captchaValid = (captcha === currentCaptcha);
    console.log(`验证码验证: ${captchaValid ? '正确' : '错误'}`);
    
    try {
      if (isRegisterMode) {
        console.log(`发送注册请求到: ${SERVER_URL}/api/auth/user/register`);
        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
          showError('邮箱格式不正确');
          return;
        }
        
        const requestData = { 
          username, 
          password, 
          email
        };
        console.log('[注册] 请求数据:', { ...requestData, password: '***' });
        
        const response = await fetch(`${SERVER_URL}/api/auth/user/register`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestData)
        });
        const result = await response.json();
        console.log('注册响应:', result);
        if (result.success) {
          showNotification('注册成功，请使用该账号登录', 'success');
          // 切回登录模式并预填用户名
          setMode('login');
          usernameInput.value = username;
          passwordInput.value = '';
          captchaInput.value = '';
          currentCaptcha = generateCaptcha();
          updateCaptchaDisplay();
        } else {
          showError(result.message || '注册失败');
        }
      } else {
        console.log(`发送登录请求到: ${SERVER_URL}/api/auth/user/login`);
        
        const requestData = { 
          username, 
          password,
          captcha: captchaValid ? 'valid' : 'invalid'
        };
        console.log('[登录] 请求数据:', { 
          username, 
          password: '***', 
          captcha: requestData.captcha
        });
        
        // 发送登录请求到服务器
        const response = await fetch(`${SERVER_URL}/api/auth/user/login`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestData)
        });

        const result = await response.json();
        console.log('服务器响应:', result);

        if (result.success) {
          // 检查验证码
          if (!captchaValid) {
            showError('验证码错误，但账号密码正确。请重新输入验证码。');
            currentCaptcha = generateCaptcha();
            updateCaptchaDisplay();
            captchaInput.value = '';
            return;
          }
          
          // 保存用户数据
          saveUserData(result.data);
          
          // 处理记住账号
          if (rememberMeCheckbox.checked) {
            localStorage.setItem('rememberedUsername', username);
          } else {
            localStorage.removeItem('rememberedUsername');
          }

          log.info(`用户 ${username} 登录成功`);
          showNotification('登录成功', 'success');

          // 🔥 通知主进程用户已登录，触发服务器连接
          ipcRenderer.send('user-logged-in');

          // 🔥 登录成功后上传客户端ID
          try {
            console.log('[登录] 开始上传客户端ID...');
            const clientId = await ipcRenderer.invoke('get-client-id');
            console.log('[登录] 客户端ID:', clientId);
            
            if (clientId) {
              const uploadResponse = await fetch(`${SERVER_URL}/api/auth/upload-client-id`, {
                method: 'POST',
                headers: { 
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${result.data.token}`
                },
                body: JSON.stringify({ client_id: clientId })
              });
              
              const uploadResult = await uploadResponse.json();
              
              // 🔥 处理409错误：账号已在其他客户端登录
              if (uploadResponse.status === 409 && uploadResult.code === 'ALREADY_LOGGED_IN') {
                console.error('[登录] 账号已在其他客户端登录');
                showError(`该账号已在其他客户端登录\n客户端ID: ${uploadResult.current_client_id || '未知'}\n每个账号只能同时登录一个客户端`);
                // 清除已保存的登录信息
                localStorage.removeItem('userData');
                currentCaptcha = generateCaptcha();
                updateCaptchaDisplay();
                captchaInput.value = '';
                return;
              }
              
              if (uploadResult.success) {
                console.log('[登录] ✅ 客户端ID上传成功');
              } else {
                console.warn('[登录] ⚠️  客户端ID上传失败:', uploadResult.message);
              }
            } else {
              console.warn('[登录] ⚠️  客户端ID为空，跳过上传');
            }
          } catch (uploadError) {
            console.error('[登录] 客户端ID上传失败:', uploadError);
            // 不阻止登录流程，只记录错误
          }

          // 延迟跳转，让用户看到成功提示
          setTimeout(() => {
            navigateToPage('main');
          }, 500);
        } else {
          // 显示服务器返回的错误
          showError(result.message || '登录失败');
          // 刷新验证码
          currentCaptcha = generateCaptcha();
          updateCaptchaDisplay();
          captchaInput.value = '';
        }
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      log.error('登录失败:', error);
      showError('网络错误，请检查服务器连接');
      // 刷新验证码
      currentCaptcha = generateCaptcha();
      updateCaptchaDisplay();
      captchaInput.value = '';
    } finally {
      loginBtn.disabled = false;
      loginBtn.textContent = isRegisterMode ? '注册' : '登录';
    }
  });

  // 回车键快捷登录
  usernameInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      passwordInput.focus();
    }
  });

  passwordInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      captchaInput.focus();
    }
  });
  
  console.log('所有事件监听器绑定完成');
}

// 设置模式：login 或 register
function setMode(mode) {
  isRegisterMode = (mode === 'register');
  if (isRegisterMode) {
    emailRow && (emailRow.style.display = 'flex');
    switchToRegisterEl && (switchToRegisterEl.style.display = 'none');
    switchToLoginEl && (switchToLoginEl.style.display = 'inline');
    formTitleEl && (formTitleEl.textContent = '注册 新账号');
    loginBtn && (loginBtn.textContent = '注册');
  } else {
    emailRow && (emailRow.style.display = 'none');
    switchToRegisterEl && (switchToRegisterEl.style.display = 'inline');
    switchToLoginEl && (switchToLoginEl.style.display = 'none');
    formTitleEl && (formTitleEl.textContent = '欢迎 回来');
    loginBtn && (loginBtn.textContent = '登录');
  }
}

// 服务器状态检测（兼容 /api/health 与 /health）
async function checkServerStatus() {
  if (!serverStatusEl) return;
  const setStatus = (text, color) => {
    serverStatusEl.textContent = `服务器状态：${text}`;
    serverStatusEl.style.color = color;
  };
  try {
    // 优先尝试 /api/health
    let res = await fetch(`${SERVER_URL}/api/health`, { method: 'GET' });
    if (!res.ok) {
      // 回退到 /health（服务端当前实现）
      res = await fetch(`${SERVER_URL}/health`, { method: 'GET' });
    }
    if (res.ok) {
      setStatus('在线', '#16a34a');
    } else {
      setStatus('异常', '#dc2626');
    }
  } catch (e) {
    setStatus('离线', '#dc2626');
  }
}
